﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO.Compression;
using XPTable;
using XPTable.Editors;
using XPTable.Models;
using WeifenLuo.WinFormsUI.Docking;
using System.Web.Security;

namespace Client
{
    public partial class Client : Form
    {

        #region 变量定义

        private string my_ip;
        private string my_port;
        private bool isadd = false;
        private bool isaddup = false;
        private bool isaddown = false;
        private bool isaddownlist = false;
        private bool isaddiary = false;
        private string user;
        private string psw;
        public System.Windows.Forms.ListView listView1;
        public System.Windows.Forms.ListView listView_down;
        private System.Windows.Forms.Button Button_up;
        private System.Windows.Forms.Button Button_down;
        TabPage myTabPage;
        TabPage myTabPage_downfiles;
        Socket_Link mylink = new Socket_Link();

        public XPTable.Models.Table table;
        public XPTable.Models.Table tableup;
        static int row = 0;
        private string savepath;
        TableModel tableModel = null;
        private Dialy dialy;
        public ToolBox m_toolbox;
        private string path;

        WeifenLuo.WinFormsUI.Docking.DockPanelSkin dockPanelSkin1 = new WeifenLuo.WinFormsUI.Docking.DockPanelSkin();
        WeifenLuo.WinFormsUI.Docking.AutoHideStripSkin autoHideStripSkin1 = new WeifenLuo.WinFormsUI.Docking.AutoHideStripSkin();
        WeifenLuo.WinFormsUI.Docking.DockPanelGradient dockPanelGradient1 = new WeifenLuo.WinFormsUI.Docking.DockPanelGradient();
        WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient1 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
        WeifenLuo.WinFormsUI.Docking.DockPaneStripSkin dockPaneStripSkin1 = new WeifenLuo.WinFormsUI.Docking.DockPaneStripSkin();
        WeifenLuo.WinFormsUI.Docking.DockPaneStripGradient dockPaneStripGradient1 = new WeifenLuo.WinFormsUI.Docking.DockPaneStripGradient();
        WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient2 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
        WeifenLuo.WinFormsUI.Docking.DockPanelGradient dockPanelGradient2 = new WeifenLuo.WinFormsUI.Docking.DockPanelGradient();
        WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient3 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
        WeifenLuo.WinFormsUI.Docking.DockPaneStripToolWindowGradient dockPaneStripToolWindowGradient1 = new WeifenLuo.WinFormsUI.Docking.DockPaneStripToolWindowGradient();
        WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient4 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
        WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient5 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
        WeifenLuo.WinFormsUI.Docking.DockPanelGradient dockPanelGradient3 = new WeifenLuo.WinFormsUI.Docking.DockPanelGradient();
        WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient6 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
        WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient7 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
        public WeifenLuo.WinFormsUI.Docking.DockPanel dockPanel1;
        public System.Windows.Forms.TabControl tabControl3;
        UserSession session;
        UserData userdata;
        #endregion

        #region 公共部分

        public Client(UserSession newsession, UserData userdata, p2p.MessageProcessor msgPro)
        {
            InitializeComponent();
            this.skinEngine1.SkinFile = "DeepCyan.ssk";
            this.session = newsession;
            this.userdata = userdata;

            if (session.Name!=""&&session.Pwd!="")
            {
                user = session.Name;
                string MD5;//MD5加密
                MD5 = FormsAuthentication.HashPasswordForStoringInConfigFile(session.Pwd, "MD5");
                psw = MD5;
            }

            this.msgPro = msgPro;
            this.msgPro.MessageReceived += new p2p.MessageReceivedEventHandler(MessageReceiver);
            this.msgPro.MessageSendingFailed += new p2p.MessageSendingFailedEventHandler(MessageSendingFailed);
            this.msgPro.MessageSent += new p2p.MessageSentEventHandler(MessageSent);
            this.msgPro.UserOnline += new p2p.UserOnlineEventHandler(OnUserOnline);
            this.msgPro.UserOffline += new p2p.UserOfflineEventHandler(OnUserOffline);
            this.msgPro.FileReceiving += new p2p.FileReceivingEventHandler(OnFileReceiving);
            foreach (KeyValuePair<string, UserData.User> user in userdata.Users)
            {
                if (user.Key == session.Name) continue;
                this.userstats.Add(user.Key, new UserStatus(false));
            }
        }

        private void Client_Load(object sender, EventArgs e)
        {
            this.Text = "欢迎用户： " + user;
            StreamReader sr = new StreamReader(System.Windows.Forms.Application.StartupPath + "\\set.txt");//, System.Text.Encoding.GetEncoding("gb2312"));
            my_ip = sr.ReadLine();
            my_port = sr.ReadLine();
            path = sr.ReadLine();
            sr.Close();

            CreateUserTreeview("不分类");
            this.msgPro.SendLogonInform();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
                this.notifyIcon1.Visible = false;
            }
        }

        private void Client_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                this.notifyIcon1.Visible = true;
            }
        }

        private void Client_FormClosed(object sender, FormClosedEventArgs e)
        {
            setinfo.Enabled = false;
            if (toolStripStatusLabel1.Text == "已连接到服务器....")
                mylink.close_link();
            else if (toolStripStatusLabel1.Text == "已连接到服务器....但无权获得信息")
                mylink.error_close_link();

            this.msgPro.SendLogoffInform();
        }

        /************************************关闭选项卡***********************************************/
        private void tabControl1_MouseDoubleClick(object sender, MouseEventArgs e)
        {

            TabControl tc = (TabControl)sender;
            TabPage tp = this.tabControl1.TabPages[tc.SelectedIndex];
            int index = tc.SelectedIndex;
            if (tp.Text == "文件列表")
            {
                isadd = false;
                listView1 = null;
                myTabPage = null;
            }
            else if (tp.Text == "上传文件列表")
            {
                row = 0;
                isaddup = false;
                tableup = null;
                tableModel = null;
                myTabPage = null;
            }
            else if (tp.Text == "下载文件列表")
            {
                isaddown = false;
                table = null;
                myTabPage = null;
            }
            else if (tp.Text == "已下载文件列表")
            {
                isaddownlist = false;
                listView_down = null;
                myTabPage_downfiles = null;
            }
            else if (tp.Text == "日志管理")
            {
                isaddiary = false;

            }
            else if ((string)tp.Tag == "PrivateChat")
            {
                PrivateChatCtrl ctrl = (PrivateChatCtrl)tp.Controls["PrivateChat"];
                if (ctrl.FileTransfering)
                {
                    DialogResult result = MessageBox.Show("有文件在传送，如果关闭此窗口，将结束传送，确定吗？", "提示", MessageBoxButtons.YesNo);
                    if (result == DialogResult.No)
                        return;
                    else
                        ctrl.CancelAllFileTransfer();
                }
            }
            this.tabControl1.TabPages.Remove(tp);
            tp.Dispose();
            if (index > 0) this.tabControl1.SelectedIndex = index - 1;
        }

        private void tabControl1_Enter(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab != null)
                if (this.listFlash.Contains(this.tabControl1.SelectedTab.Name))
                {
                    this.listFlash.Remove(this.tabControl1.SelectedTab.Name);
                }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab != null)
            {
                string name = this.tabControl1.SelectedTab.Name;
                if (this.listFlash.Contains(name))
	            {
                    Control[] nodes = this.treeViewUsers.Controls.Find(name, true);
                    foreach (Control node in nodes)
                    {
                        node.Text = node.Name;
                    }
                    this.tabControl1.SelectedTab.Text = "与 " + name + " 聊天中";
                    this.listFlash.Remove(name);
	            }
            }
        }

        #endregion

        #region PS结构部分

        /***********************************************************************************************/
        /*           
         *                 连接服务器 
        /*********************************************************************************************/

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                isadd = false;
                mylink.getip = my_ip;
                mylink.getport = my_port;
                mylink.getree = tree_show_file;
                mylink.getuser = user;
                mylink.getpsw = psw;
                mylink.getform = this;
                if (mylink.BindPort()) // 绑定端口，开始连接主机
                {
                    toolStripButton1.Enabled = false;
                    toolStripButton2.Enabled = true;
                    upload.Enabled = true;
                    download.Enabled = true;
                    文件上传ToolStripMenuItem.Enabled = true;
                    文件下载ToolStripMenuItem.Enabled = true;
                    toolStripStatusLabel2.Image = global::Client.Properties.Resources.led_green;
                    toolStripStatusLabel3.Image = global::Client.Properties.Resources.led_off;
                }
            }
            catch { }
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            psw = mylink.getpsw;
            user = mylink.getuser;
            toolStripButton2.Enabled = false;
            toolStripButton1.Enabled = true;
            upload.Enabled = false;
            download.Enabled = false;
            文件上传ToolStripMenuItem.Enabled = false;
            文件下载ToolStripMenuItem.Enabled = false;

            toolStripStatusLabel3.Image = global::Client.Properties.Resources.led_red;
            toolStripStatusLabel2.Image = global::Client.Properties.Resources.led_off;
            setinfo.Enabled = false;
            if (toolStripStatusLabel1.Text == "已连接到服务器....")
            {
                mylink.close_link();
                toolStripStatusLabel1.Text = "已断开与服务器的连接....";
            }
            else
            {
                mylink.error_close_link();
                toolStripStatusLabel1.Text = "已断开与服务器的连接....";
            }
        }

        private void 连接属性设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            link open = new link();
            open.ShowDialog();
            if (open.ip != null && open.port != null)
            {
                my_ip = open.ip;
                my_port = open.port;
            }
        }
        private void tree_show_file_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (tree_show_file.SelectedNode != null && tree_show_file.SelectedNode.ImageIndex == 2)
            {
                savepath = tree_show_file.SelectedNode.Text.ToString();
                mylink.getupload_filesavepath = savepath;
            }
        }
        private void tree_show_file_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (tree_show_file.SelectedNode != null && tree_show_file.SelectedNode.ImageIndex == 2)
                {
                    if (isadd == false)
                    {
                        myTabPage = new TabPage("文件列表");
                        tabControl1.TabPages.Add(myTabPage);
                        listView1 = new ListView();
                        this.listView1.Dock = System.Windows.Forms.DockStyle.Fill;
                        this.listView1.LargeImageList = this.imageList2;
                        this.listView1.Location = new System.Drawing.Point(3, 3);
                        this.listView1.Name = "listView1";
                        this.listView1.Size = new System.Drawing.Size(442, 421);
                        this.listView1.SmallImageList = this.imageList2;
                        this.listView1.TabIndex = 0;
                        this.listView1.ContextMenuStrip = this.contextMenuStrip1;// this.tree_show_file.ContextMenuStrip = this.contextMenuStrip1;
                        this.listView1.UseCompatibleStateImageBehavior = false;
                        this.listView1.ItemSelectionChanged += new System.Windows.Forms.ListViewItemSelectionChangedEventHandler(this.listView1_ItemSelectionChanged);
                        listView1.Parent = myTabPage;
                        tabControl1.SelectedIndex = tabControl1.TabCount - 1;

                        mylink.getlistview = listView1;
                        mylink.gettabpage = myTabPage;//载入控件信息
                        isadd = true;
                    }
                    mylink.wantfiles(tree_show_file.SelectedNode.Tag.ToString());//获取文件信息
                }
            }
        }

        private void 断开连接ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStripButton2_Click(sender, e);
        }

        private void setinfo_Click(object sender, EventArgs e)
        {
            set_info open = new set_info(mylink.getsocket,mylink.info,mylink.getuser);
            open.Show();
        }

        private void download_Click(object sender, EventArgs e)
        {
            if(listView1!=null){
                if (listView1.SelectedItems.Count > 0)
                {
                    if (isaddown == false)
                    {
                        myTabPage = new TabPage("下载文件列表");
                        tabControl1.TabPages.Add(myTabPage);
                        this.table = new Table();

                        this.table.AlternatingRowColor = System.Drawing.Color.FromArgb(((int)(((byte)(230)))), ((int)(((byte)(237)))), ((int)(((byte)(245)))));
                        this.table.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(237)))), ((int)(((byte)(242)))), ((int)(((byte)(249)))));
                        this.table.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                           | System.Windows.Forms.AnchorStyles.Right | System.Windows.Forms.AnchorStyles.Bottom)));
                        this.table.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(14)))), ((int)(((byte)(66)))), ((int)(((byte)(121)))));
                        this.table.GridColor = System.Drawing.SystemColors.ControlDark;
                        this.table.GridLines = XPTable.Models.GridLines.Both;
                        this.table.GridLineStyle = XPTable.Models.GridLineStyle.Dot;
                        this.table.HeaderFont = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                        this.table.Location = new System.Drawing.Point(0, 0);
                        this.table.Name = "table";
                        this.table.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(169)))), ((int)(((byte)(183)))), ((int)(((byte)(201)))));
                        this.table.SelectionForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(14)))), ((int)(((byte)(66)))), ((int)(((byte)(121)))));
                        this.table.SelectionStyle = XPTable.Models.SelectionStyle.Grid;
                        this.table.Size = new System.Drawing.Size(myTabPage.Size.Width, myTabPage.Size.Height - 50);
                        this.table.SortedColumnBackColor = System.Drawing.Color.Transparent;
                        this.table.TabIndex = 0;
                        this.table.Text = "table";
                        this.table.UnfocusedSelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(201)))), ((int)(((byte)(210)))), ((int)(((byte)(221)))));
                        this.table.UnfocusedSelectionForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(14)))), ((int)(((byte)(66)))), ((int)(((byte)(121)))));
                        table.Parent = myTabPage;
                        tabControl1.SelectedIndex = tabControl1.TabCount - 1;
                        isaddown = true;
                        ColumnModel columnModel = new ColumnModel();
                        columnModel.Columns.Add(new CheckBoxColumn("下载", 100));
                        columnModel.Columns.Add(new TextColumn("文件名", 140));
                        columnModel.Columns.Add(new ProgressBarColumn("传输进度", 320));
                        columnModel.Columns.Add(new TextColumn("传输量/文件大小", 140));
                        this.table.ColumnModel = columnModel;

                        Button_down = new Button();
                        this.Button_down.Location = new System.Drawing.Point(myTabPage.Size.Width - 100, myTabPage.Size.Height - 30);
                        this.Button_down.Name = "down_ok";
                        this.Button_down.Size = new System.Drawing.Size(75, 23);
                        this.Button_down.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Right | System.Windows.Forms.AnchorStyles.Bottom))));
                        this.Button_down.TabIndex = 1;
                        this.Button_down.Text = "确定";
                        this.Button_down.UseVisualStyleBackColor = true;
                        Button_down.Parent = myTabPage;
                        this.Button_down.Click += new System.EventHandler(this.Button_down_Click);
                    }
                    if (this.table != null)
                    {
                        TableModel tableModel1 = new TableModel();
                        for (int i = 0; i < listView1.SelectedItems.Count && listView1.SelectedItems[i].Text != ""; i++)
                        {
                            tableModel1.Rows.Add(new Row());
                            tableModel1.Rows[i].Cells.Add(new Cell("确定/取消"));
                            tableModel1.Rows[i].Cells.Add(new Cell(listView1.SelectedItems[i].Text.ToString()));
                            tableModel1.Rows[i].Cells.Add(new Cell("传输进度"));
                            tableModel1.Rows[i].Cells.Add(new Cell("0.0 MB/0.0 MB"));
                            tableModel1.Rows[i].Cells[0].Tag = listView1.SelectedItems[i].Tag;
                            tableModel1.RowHeight = 20;
                            tableModel1.Rows[i].Cells[0].Checked = true;
                            this.table.TableModel = tableModel1;
                        }
                    }
                }
            }
        }

        private string select(string filename) 
        {
            string[] retures = filename.Split(new char[] { '\\'});
            int n=retures.Length;
            string name=retures[n-1];
            return name;
        }
        private void upload_Click(object sender, EventArgs e)
        {
            openFileDialog1.Title = "选择上传文件";
            openFileDialog1.Multiselect = true;
            if ((openFileDialog1.ShowDialog() == DialogResult.OK))
            {
                if (isaddup == false)
                {
                    myTabPage = new TabPage("上传文件列表");
                    tabControl1.TabPages.Add(myTabPage);
                    this.tableup = new Table();
                    this.tableup.AlternatingRowColor = System.Drawing.Color.FromArgb(((int)(((byte)(230)))), ((int)(((byte)(237)))), ((int)(((byte)(245)))));
                    this.tableup.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(237)))), ((int)(((byte)(242)))), ((int)(((byte)(249)))));
                    this.tableup.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                       | System.Windows.Forms.AnchorStyles.Right | System.Windows.Forms.AnchorStyles.Bottom)));
                    this.tableup.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(14)))), ((int)(((byte)(66)))), ((int)(((byte)(121)))));
                    this.tableup.GridColor = System.Drawing.SystemColors.ControlDark;
                    this.tableup.GridLines = XPTable.Models.GridLines.Both;
                    this.tableup.GridLineStyle = XPTable.Models.GridLineStyle.Dot;
                    this.tableup.HeaderFont = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    this.tableup.Location = new System.Drawing.Point(0, 0);
                    this.tableup.Name = "tableup";
                    this.tableup.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(169)))), ((int)(((byte)(183)))), ((int)(((byte)(201)))));
                    this.tableup.SelectionForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(14)))), ((int)(((byte)(66)))), ((int)(((byte)(121)))));
                    this.tableup.SelectionStyle = XPTable.Models.SelectionStyle.Grid;
                    this.tableup.Size = new System.Drawing.Size(myTabPage.Size.Width, myTabPage.Size.Height - 50);
                    this.tableup.SortedColumnBackColor = System.Drawing.Color.Transparent;
                    this.tableup.TabIndex = 0;
                    this.tableup.Text = "table";
                    this.tableup.CellMouseDown += new XPTable.Events.CellMouseEventHandler(this.tableup_CellMouseDown);
                    this.tableup.UnfocusedSelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(201)))), ((int)(((byte)(210)))), ((int)(((byte)(221)))));
                    this.tableup.UnfocusedSelectionForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(14)))), ((int)(((byte)(66)))), ((int)(((byte)(121)))));

                    tableup.Parent = myTabPage;
                    tabControl1.SelectedIndex = tabControl1.TabCount - 1;
                    isaddup = true;
                    ColumnModel columnModel = new ColumnModel();
                    columnModel.Columns.Add(new CheckBoxColumn("确定上传项", 85));
                    columnModel.Columns.Add(new TextColumn("文件名", 130, true));
                    columnModel.Columns.Add(new ProgressBarColumn("传输进度", 260, true));
                    columnModel.Columns.Add(new TextColumn("传输量/文件大小", 140, true));
                    columnModel.Columns.Add(new ButtonColumn("浏览", 50, true));
                    this.tableup.ColumnModel = columnModel;
                    tableModel = new TableModel();

                    Button_up = new Button();
                    this.Button_up.Location = new System.Drawing.Point(myTabPage.Size.Width - 100, myTabPage.Size.Height - 30);
                    this.Button_up.Name = "ok";
                    this.Button_up.Size = new System.Drawing.Size(75, 23);
                    this.Button_up.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Right | System.Windows.Forms.AnchorStyles.Bottom))));
                    this.Button_up.TabIndex = 1;
                    this.Button_up.Text = "确定";
                    this.Button_up.UseVisualStyleBackColor = true;
                    Button_up.Parent = myTabPage;
                    this.Button_up.Click += new System.EventHandler(this.Button_up_Click);
                }
                if (tableup != null && tableModel != null)
                {

                    foreach (string strFilename in openFileDialog1.FileNames)
                    {
                        tableModel.Rows.Add(new Row());
                        tableModel.Rows[row].Cells.Add(new Cell("确定/取消"));
                        tableModel.Rows[row].Cells.Add(new Cell(select(strFilename)));
                        tableModel.Rows[row].Cells.Add(new Cell("传输进度"));

                        float filesize = 0;
                        string strsize = "";
                        FileInfo fileinfo = new FileInfo(strFilename);
                        filesize = fileinfo.Length;
                        if (filesize <= 1024 * 1024)
                        {
                            filesize = filesize / 1024;
                            strsize = filesize.ToString() + "KB";
                        }
                        else if (filesize > 1024 * 1024)
                        {
                            filesize = filesize / (1024 * 1024);
                            strsize = filesize.ToString("0.0#") + "MB";
                        }
                        tableModel.Rows[row].Cells.Add(new Cell("0.0 MB/" + strsize));
                        tableModel.Rows[row].Cells.Add(new Cell("浏览"));
                        tableModel.Rows[row].Cells[0].Tag = strFilename;
                        tableModel.RowHeight = 20;
                        tableModel.Rows[row].Cells[0].Checked = true;
                        this.tableup.TableModel = tableModel;
                        row++;
                    }
                }
            }
        }
        private bool CheckFileName(string filename)
        {
            
            string[] get = filename.Split(new char[] { '-' });
             string[] get2 = filename.Split(new char[] { '|' });
            if (get.Length>1||get2.Length>1)
            {
                return false;
            }
            else 
            {
                return true;
            }
            
        }
        private void Button_up_Click(object sender, EventArgs e)
        {
            if (tree_show_file==null||tree_show_file.SelectedNode == null || tree_show_file.SelectedNode.ImageIndex != 2)
            {
                MessageBox.Show("请正确选择上传路径");
                return;
            }
            else
            {
                if (tree_show_file.SelectedNode.Text == user)
                {
                    for (int x=0;x < this.tableup.RowCount; x++)
                    {
                        if (tableup.TableModel.Rows[x].Cells[0].Checked == true && CheckFileName(tableup.TableModel.Rows[x].Cells[1].Text) == false)
                        {
                            MessageBox.Show("文件名中不能含有\"-\"或者\"|\"");
                            return;
                        }
                    }
                   
                    int i;
                    savepath = tree_show_file.SelectedNode.Tag.ToString();
                    for (i = 0; i < this.tableup.RowCount; i++)
                    {
                        if (tableup.TableModel.Rows[i].Cells[0].Checked == true && tableup.TableModel.Rows[i].Cells[0].Enabled == true)
                        {
                            break;
                        }
                    }

                    if (i != this.tableup.RowCount && tableup.TableModel.Rows[i].Cells[0].Checked == true && tableup.TableModel.Rows[i].Cells[0].Enabled == true)
                    {
                        mylink.getupload_filename = tableup.TableModel.Rows[i].Cells[1].Text;//传参：文件名称
                        mylink.getupload_filepath = tableup.TableModel.Rows[i].Cells[0].Tag.ToString();//传参：文件存储路径
                        mylink.getupload_filenumber = i;//传参：文件序列
                        mylink.getupload_filesavepath = savepath;//文件上传时存储路径
                        mylink.sendmessage("upload|" + user.ToString() + "|" + savepath + "|");
                        tableup.TableModel.Rows[i].Cells[0].Enabled = false;
                    }
                }
                else 
                {
                    MessageBox.Show("只能向您参与的项目中添加文件，不能向其他用户中添加文件！");
                    return;
                }
            }
        }

        private void tableup_CellMouseDown(object sender, XPTable.Events.CellMouseEventArgs e)
        {
            if (e.Column == 4)
            {
                try
                {
                    System.Diagnostics.Process.Start(this.tableup.TableModel.Rows[e.Row].Cells[0].Tag.ToString());
                }
                catch
                {
                    MessageBox.Show("不支持该文件格式，无法打开文件");
                }
            }
        }

        private void listView_down_DoubleClick(object sender, EventArgs e)
        {
            if (listView_down != null)
            {
                if (listView_down.SelectedItems.Count == 1)
                {
                    try
                    {
                        System.Diagnostics.Process.Start(listView_down.SelectedItems[0].Tag.ToString());
                    }
                    catch
                    {
                        MessageBox.Show("不支持该文件格式，无法打开文件");
                    }
                }
            }
        }   
        private void Button_down_Click(object sender, EventArgs e)
        {
            if (listView1 != null)
            {
                folderBrowserDialog1.Description = "选择下载存储路径";

                if (isaddownlist == false)
                {
                    myTabPage_downfiles = new TabPage("已下载文件列表");
                    tabControl1.TabPages.Add(myTabPage_downfiles);
                    listView_down = new ListView();
                    this.listView_down.Dock = System.Windows.Forms.DockStyle.Fill;
                    this.listView_down.GridLines = true;
                    this.listView_down.LargeImageList = this.imageList3;
                    this.listView_down.Location = new System.Drawing.Point(3, 3);
                    this.listView_down.Name = "downloaden";
                    this.listView_down.Size = new System.Drawing.Size(442, 421);
                    this.listView_down.SmallImageList = this.imageList3;
                    this.listView_down.FullRowSelect = true;
                    this.listView_down.ContextMenuStrip = this.contextMenuStrip3;
                    this.listView_down.TabIndex = 0;
                    this.listView_down.UseCompatibleStateImageBehavior = false;
                    this.listView_down.View = System.Windows.Forms.View.Details;
                    this.listView_down.DoubleClick += new System.EventHandler(this.listView_down_DoubleClick);
                    this.listView_down.ItemSelectionChanged += new System.Windows.Forms.ListViewItemSelectionChangedEventHandler(this.listView_down_ItemSelectionChanged);
                    listView_down.Parent = myTabPage_downfiles;

                    mylink.getlistviewdown = listView_down;//载入控件信息 
                    isaddownlist = true;
                }

                if ((folderBrowserDialog1.ShowDialog() == DialogResult.OK))
                {
                    string downloadsavepath = folderBrowserDialog1.SelectedPath.ToString();
                    int i;
                    for (i = 0; i < this.table.RowCount; i++)
                    {
                        if (table.TableModel.Rows[i].Cells[0].Checked == true && table.TableModel.Rows[i].Cells[0].Enabled == true)
                        {
                            break;
                        }
                    }
                   
                    if (table.TableModel.Rows[i].Cells[0].Checked == true&&table.TableModel.Rows[i].Cells[0].Enabled == true)
                    {
                        mylink.getdownload_filename = table.TableModel.Rows[i].Cells[1].Text;//传参：文件名称
                        mylink.getdownload_filepath = table.TableModel.Rows[i].Cells[0].Tag.ToString();//传参：文件存储路径
                        mylink.getdownload_filenumber = i;//传参：文件序列
                        mylink.getdownload_filesavepath = downloadsavepath+"\\";//文件下载后时存储路径
                        mylink.sendmessage("download|" + user.ToString() +
                            "|" + table.TableModel.Rows[i].Cells[0].Tag.ToString() + "|"
                            + table.TableModel.Rows[i].Cells[1].Text + "|");
                        table.TableModel.Rows[i].Cells[0].Enabled = false;
                    }
                }
            }
        }

        private void listView_down_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (listView_down.SelectedItems.Count == 1)
            {
                openpath.Enabled = true;
                openfile.Enabled = true;
            }
            else
            {
                openpath.Enabled = false;
                openfile.Enabled = false;
            }
        }

        //从文件路径中找到具体的成员姓名
        private string selectusername(string fullname) 
        {
            string[] get = fullname.Split(new char[] {'\\' });
            string name = get[get.Length - 2];
            return name;
        }
        private void delete_Click(object sender, EventArgs e)
        {
            if (selectusername(listView1.SelectedItems[0].Tag.ToString()) == user.ToString())
            {
                DialogResult result = MessageBox.Show("是否确认要删除该文件", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    mylink.sendmessage("deletefile|" + user.ToString() +
                               "|" + listView1.SelectedItems[0].Tag.ToString() + "|");
                }
            }
            else
            {
                MessageBox.Show("无权删除其他项目成员的文件");
                return;
            }
        }

        private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                delete.Enabled = true;
            }
            else 
            {
                delete.Enabled = false;
            }
        }

        private void 显示主窗口ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.notifyIcon1.Visible = false;
        }

        private void 退出系统ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void openfile_Click(object sender, EventArgs e)
        {
            if (listView_down != null)
            {
                if (listView_down.SelectedItems.Count == 1)
                {
                    try
                    {
                        System.Diagnostics.Process.Start(listView_down.SelectedItems[0].Tag.ToString());
                    }
                    catch
                    {
                        MessageBox.Show("不支持该文件格式，无法打开文件");
                    }
                }
            }
        }

        //构造文件所在文件夹路径
        private string selectpath(string path)
        {
            string[] get = path.Split(new char[] { '\\' });
            string wantpath = "";
            for (int i = 0; i < get.Length - 1; i++)
            {
                wantpath = wantpath + get[i] + "\\";
            }
            return wantpath;
        }

        private void openpath_Click(object sender, EventArgs e)
        {
            if (listView_down.SelectedItems.Count == 1)
            {
                try
                {
                    System.Diagnostics.Process.Start(selectpath(listView_down.SelectedItems[0].Tag.ToString()));
                }
                catch
                {
                    MessageBox.Show("路径错误");
                }
            }
        }

        private void 撰写管理日志ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StreamReader sr = new StreamReader(System.Windows.Forms.Application.StartupPath + "\\set.txt");//, System.Text.Encoding.GetEncoding("gb2312"));
            sr.ReadLine();
            sr.ReadLine();
            path = sr.ReadLine();
            sr.Close();
            if (path == null)
            {
                MessageBox.Show("请首先设置日志根目录");
                return;
            }
            else
            {
                if (isaddiary == false)
                {
                    myTabPage = new TabPage("日志管理");
                    tabControl1.TabPages.Add(myTabPage);
                    dockPanel1 = new DockPanel();

                    this.dockPanel1.ActiveAutoHideContent = null;
                    this.dockPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
                    this.dockPanel1.DockBackColor = System.Drawing.Color.Transparent;
                    this.dockPanel1.Location = new System.Drawing.Point(3, 3);
                    this.dockPanel1.Name = "dockPanel1";
                    this.dockPanel1.Size = new System.Drawing.Size(524, 427);
                    dockPanelGradient1.EndColor = System.Drawing.SystemColors.ControlLight;
                    dockPanelGradient1.StartColor = System.Drawing.SystemColors.ControlLight;
                    autoHideStripSkin1.DockStripGradient = dockPanelGradient1;
                    tabGradient1.EndColor = System.Drawing.SystemColors.Control;
                    tabGradient1.StartColor = System.Drawing.SystemColors.Control;
                    tabGradient1.TextColor = System.Drawing.SystemColors.ControlDarkDark;
                    autoHideStripSkin1.TabGradient = tabGradient1;
                    dockPanelSkin1.AutoHideStripSkin = autoHideStripSkin1;
                    tabGradient2.EndColor = System.Drawing.SystemColors.ControlLightLight;
                    tabGradient2.StartColor = System.Drawing.SystemColors.ControlLightLight;
                    tabGradient2.TextColor = System.Drawing.SystemColors.ControlText;
                    dockPaneStripGradient1.ActiveTabGradient = tabGradient2;
                    dockPanelGradient2.EndColor = System.Drawing.SystemColors.Control;
                    dockPanelGradient2.StartColor = System.Drawing.SystemColors.Control;
                    dockPaneStripGradient1.DockStripGradient = dockPanelGradient2;
                    tabGradient3.EndColor = System.Drawing.SystemColors.ControlLight;
                    tabGradient3.StartColor = System.Drawing.SystemColors.ControlLight;
                    tabGradient3.TextColor = System.Drawing.SystemColors.ControlText;
                    dockPaneStripGradient1.InactiveTabGradient = tabGradient3;
                    dockPaneStripSkin1.DocumentGradient = dockPaneStripGradient1;
                    tabGradient4.EndColor = System.Drawing.SystemColors.ActiveCaption;
                    tabGradient4.LinearGradientMode = System.Drawing.Drawing2D.LinearGradientMode.Vertical;
                    tabGradient4.StartColor = System.Drawing.SystemColors.GradientActiveCaption;
                    tabGradient4.TextColor = System.Drawing.SystemColors.ActiveCaptionText;
                    dockPaneStripToolWindowGradient1.ActiveCaptionGradient = tabGradient4;
                    tabGradient5.EndColor = System.Drawing.SystemColors.Control;
                    tabGradient5.StartColor = System.Drawing.SystemColors.Control;
                    tabGradient5.TextColor = System.Drawing.SystemColors.ControlText;
                    dockPaneStripToolWindowGradient1.ActiveTabGradient = tabGradient5;
                    dockPanelGradient3.EndColor = System.Drawing.SystemColors.ControlLight;
                    dockPanelGradient3.StartColor = System.Drawing.SystemColors.ControlLight;
                    dockPaneStripToolWindowGradient1.DockStripGradient = dockPanelGradient3;
                    tabGradient6.EndColor = System.Drawing.SystemColors.GradientInactiveCaption;
                    tabGradient6.LinearGradientMode = System.Drawing.Drawing2D.LinearGradientMode.Vertical;
                    tabGradient6.StartColor = System.Drawing.SystemColors.GradientInactiveCaption;
                    tabGradient6.TextColor = System.Drawing.SystemColors.ControlText;
                    dockPaneStripToolWindowGradient1.InactiveCaptionGradient = tabGradient6;
                    tabGradient7.EndColor = System.Drawing.Color.Transparent;
                    tabGradient7.StartColor = System.Drawing.Color.Transparent;
                    tabGradient7.TextColor = System.Drawing.SystemColors.ControlDarkDark;
                    dockPaneStripToolWindowGradient1.InactiveTabGradient = tabGradient7;
                    dockPaneStripSkin1.ToolWindowGradient = dockPaneStripToolWindowGradient1;
                    dockPanelSkin1.DockPaneStripSkin = dockPaneStripSkin1;
                    this.dockPanel1.Skin = dockPanelSkin1;
                    this.dockPanel1.TabIndex = 0;
                    dockPanel1.Parent = myTabPage;
                    this.tabControl3 = new System.Windows.Forms.TabControl();
                    this.SuspendLayout();

                    this.tabControl3.Alignment = System.Windows.Forms.TabAlignment.Bottom;
                    this.tabControl3.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                                | System.Windows.Forms.AnchorStyles.Left)
                                | System.Windows.Forms.AnchorStyles.Right)));
                    this.tabControl3.Dock = System.Windows.Forms.DockStyle.Fill;
                    this.tabControl3.Name = "tabControl2";
                    this.tabControl3.SelectedIndex = 0;
                    this.tabControl3.Size = new System.Drawing.Size(500, 393);
                    this.tabControl3.TabIndex = 2;
                    this.tabControl3.Parent = dockPanel1;
                    this.tabControl3.DoubleClick += new System.EventHandler(this.tabControl3_DoubleClick);
                    this.tabControl3.Location = new System.Drawing.Point(3, 30);
                    tabControl1.SelectedIndex = tabControl1.TabCount - 1;
                    this.ResumeLayout(false);
                    this.PerformLayout();

                    m_toolbox = new ToolBox(this, path);
                    m_toolbox.Show(dockPanel1);
                    isaddiary = true;
                }
            }
        }

        private void 设置日志根目录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetDiaryM open = new SetDiaryM();
            open.ShowDialog();
        }

        private void tabControl3_DoubleClick(object sender, EventArgs e)
        {
            string title;
            title = tabControl3.SelectedTab.Text;
            string[] titles = title.Split(new char[] { '*' });
            if (titles.Length > 1)
            {
                DialogResult ret = MessageBox.Show("该文件还没保存,确定关闭？", "确定关闭", MessageBoxButtons.OKCancel);
                if (ret == DialogResult.OK)
                {
                    TabControl tc = (TabControl)sender;
                    TabPage tp = this.tabControl3.TabPages[tc.SelectedIndex];
                    this.tabControl3.TabPages.Remove(tp);
                }
                else
                {
                    return;
                }
            }
            else
            {
                TabControl tc = (TabControl)sender;
                TabPage tp = this.tabControl3.TabPages[tc.SelectedIndex];
                this.tabControl3.TabPages.Remove(tp);
            }
        }
        private void 文件上传ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            upload_Click(sender, e);
        }

        private void 文件下载ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            download_Click(sender, e);
        }
        #endregion

        #region 局域网部分

        internal class UserStatus
        {
            public bool online;
            public Queue<p2p.Message> Messages = new Queue<p2p.Message>();
            public UserStatus(bool online)
            {
                this.online = online;
            }
        }
        private Dictionary<string, UserStatus> userstats = new Dictionary<string, UserStatus>();
        private p2p.MessageProcessor msgPro;
        private string classified = "不分类";
        private List<string> listFlash = new List<string>();
        private bool flashOn = true;

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        public static extern bool FlashWindow(
            IntPtr hWnd, // handle to window 
            bool bInvert // flash status 
        );

        [System.Runtime.InteropServices.DllImport("winmm.dll")]
        public static extern bool PlaySound(string pszSound, int hmod, int fdwSound);//播放windows音乐，重载
        public const int SND_FILENAME = 0x00020000;
        public const int SND_ASYNC = 0x0001;

        private void 不分类ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!this.不分类ToolStripMenuItem.Checked)
            {
	            this.不分类ToolStripMenuItem.Checked = true;
	            this.以项目分类ToolStripMenuItem.Checked = false;
                this.classified = "不分类";
                CreateUserTreeview(this.classified);
            }
        }

        private void 以项目分类ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!this.以项目分类ToolStripMenuItem.Checked)
            {
                this.不分类ToolStripMenuItem.Checked = false;
                this.以项目分类ToolStripMenuItem.Checked = true;
                this.classified = "以项目分类";
                CreateUserTreeview(this.classified);
            }
        }

        private void RefreshUserTreeview(string username, string classified)
        {
            if (classified == "不分类")
            {
                int index = this.treeViewUsers.Nodes.IndexOfKey(username);
                ChangeTreenodeSorted(this.treeViewUsers.Nodes, this.treeViewUsers.Nodes[index]);
            }
            else if (classified == "以项目分类")
            {
                foreach (TreeNode nodeproj in this.treeViewUsers.Nodes)
                {
                    int index = nodeproj.Nodes.IndexOfKey(username);
                    if (index >= 0)
                    {
                        ChangeTreenodeSorted(nodeproj.Nodes, nodeproj.Nodes[index]);
                    }
                }
            }
        }

        private void ChangeTreenodeSorted(TreeNodeCollection nodes, TreeNode node)
        {
            int i = nodes.IndexOf(node);
            if (i >= 0)
            {
                nodes.RemoveAt(i);
            }
            for (i = 0; i < nodes.Count; i++)
            {
                if (((UserStatus)nodes[i].Tag).online == ((UserStatus)node.Tag).online && nodes[i].Text.CompareTo(node.Text) < 0)
                    continue;
                break;
            }
            node.ImageIndex = ((UserStatus)node.Tag).online ? 1 : 0;
            node.SelectedImageIndex = node.ImageIndex;
            nodes.Insert(i, node);
        }

        private void CreateUserTreeview(string classified)
        {
            this.treeViewUsers.Nodes.Clear();
            if (classified == "不分类")
            {
                foreach (KeyValuePair<string, UserData.User> user in userdata.Users)
                {
                    if (user.Key == this.session.Name) continue;
                    TreeNode node = new TreeNode(user.Key, 0, 0);
                    node.Tag = this.userstats[user.Key];
                    node.Name = node.Text;
                    ChangeTreenodeSorted(this.treeViewUsers.Nodes, node);
                }
            }
            else if (classified == "以项目分类")
            {
                foreach (KeyValuePair<string, UserData.User> user in userdata.Users)
                {
                    if (user.Key == this.session.Name) continue;
                    foreach (UserData.UserAssignProj userassp in user.Value.AssignProj)
                    {
                        TreeNode node = new TreeNode(user.Key, 0, 0);
                        node.Tag = this.userstats[user.Key];
                        node.Name = node.Text;
                        UserData.Project proj = userdata.Projects[userassp.ProjId];
                        int index = this.treeViewUsers.Nodes.IndexOfKey(proj.ProjId.ToString());
                        if (index == -1)
                        {
                            ChangeTreenodeSorted(this.treeViewUsers.Nodes.Add(proj.ProjId.ToString(), proj.ProjName).Nodes, node);
                        }
                        else
                        {
                            ChangeTreenodeSorted(this.treeViewUsers.Nodes[index].Nodes, node);
                        }
                    }
                }
            }
        }

        private PrivateChatCtrl TriggerPrivateChat(string LocalName, string TargetName)
        {
            int index = this.tabControl1.Controls.IndexOfKey(TargetName);
            if (index >= 0)
            {
                this.tabControl1.Controls[index].Text = "与 " + TargetName + " 聊天中";
                this.tabControl1.SelectedIndex = index;
                PrivateChatCtrl ctrl = (PrivateChatCtrl)this.tabControl1.Controls[index].Controls["PrivateChat"];
                ctrl.EditBoxFocus();
                return ctrl;
            }
            else
            {
                PrivateChatCtrl ctrl = new PrivateChatCtrl(session.Name, TargetName, this.msgPro);
                ctrl.Dock = DockStyle.Fill;
                ctrl.Name = "PrivateChat";
                ctrl.Tag = this.userstats[TargetName];
                TabPage tabPageTmp = new TabPage("与 " + TargetName + " 聊天中");
                tabPageTmp.Name = TargetName;
                tabPageTmp.Tag = "PrivateChat";
                tabPageTmp.Controls.Add(ctrl);
                this.tabControl1.Controls.Add(tabPageTmp);
                this.tabControl1.SelectedTab = tabPageTmp;
                ctrl.EditBoxFocus();
                return ctrl;
            }
        }

        private PrivateChatCtrl TriggerPrivateChat(p2p.Message msg, bool focus)
        {
            int index = this.tabControl1.Controls.IndexOfKey(msg.SenderName);
            if (index >= 0)
            {
                PrivateChatCtrl ctrl = (PrivateChatCtrl)this.tabControl1.Controls[index].Controls["PrivateChat"];
                ctrl.AddMessage(msg.Time, msg.SenderName, msg.Content);
                if (focus)
                {
                    this.tabControl1.Controls[index].Text = "与 " + msg.SenderName + " 聊天中";
                    this.tabControl1.SelectedIndex = index;
                    ctrl.EditBoxFocus();
                }
                return ctrl;
            }
            else
            {
                PrivateChatCtrl ctrl = new PrivateChatCtrl(session.Name, msg.SenderName, this.msgPro);
                ctrl.Dock = DockStyle.Fill;
                ctrl.Name = "PrivateChat";
                ctrl.Tag = this.userstats[msg.SenderName];
                ctrl.AddMessage(msg.Time, msg.SenderName, msg.Content);
                TabPage tabPageTmp = new TabPage("与 " + msg.SenderName + " 聊天中");
                tabPageTmp.Name = msg.SenderName;
                tabPageTmp.Tag = "PrivateChat";
                tabPageTmp.Controls.Add(ctrl);
                this.tabControl1.Controls.Add(tabPageTmp);
                if (focus)
                {
                    this.tabControl1.SelectedTab = tabPageTmp;
                    ctrl.EditBoxFocus();
                }
                return ctrl;
            }
        }

        private void MessageSent(object sender, p2p.MessageEventArgs e)
        {
            p2p.Message msg = e.Msg;
            //未定义
        }

        private void MessageSendingFailed(object sender, p2p.MessageEventArgs e)
        {
            p2p.Message msg = e.Msg;
            TriggerPrivateChat(msg, false);
            //未完全解决
        }

        private void MessageReceiver(object sender, p2p.MessageEventArgs e)
        {
            p2p.Message msg = e.Msg;
            //TriggerPrivateChat(msg);
            int index = this.tabControl1.Controls.IndexOfKey(msg.SenderName);
            if (index >= 0)
            {
                TriggerPrivateChat(msg, false);
                if (this.tabControl1.SelectedIndex != index)
                {
                    if (!this.listFlash.Contains(msg.SenderName))
                    {
                        this.listFlash.Add(msg.SenderName);
                    }
                }
            }
            else
            {
                this.userstats[msg.SenderName].Messages.Enqueue(msg);
                if (!this.listFlash.Contains(msg.SenderName))
                {
                    this.listFlash.Add(msg.SenderName);
                }
            }
            FlashWindow(this.Handle, true);
            //TODO 加上声音
            string strPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            strPath = strPath + "\\msg.wav";
            PlaySound(strPath, 0, SND_ASYNC | SND_FILENAME);//播放音乐
        }

        private void treeViewUsers_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button != MouseButtons.Left)
                return;
            if (e.Node == null)
                return;
            UserStatus status = e.Node.Tag as UserStatus;
            if (status != null)
            {
                if (this.listFlash.Contains(e.Node.Name))
                {
	                if (status.Messages.Count != 0)
	                {
		                while(status.Messages.Count != 0)
		                {
		                    TriggerPrivateChat(status.Messages.Dequeue(), true);
		                }
	                }
                    else
                    {
                        TriggerPrivateChat(this.session.Name, e.Node.Name);
                    }
                }
                else
                {
                    TriggerPrivateChat(this.session.Name, e.Node.Name);
                }
            }
        }

        private void OnUserOffline(object sender, p2p.UserEventArgs e)
        {
            this.userstats[e.Username].online = false;
            RefreshUserTreeview(e.Username, this.classified);
        }

        private void OnUserOnline(object sender, p2p.UserEventArgs e)
        {
            this.userstats[e.Username].online = true;
            RefreshUserTreeview(e.Username, this.classified);
        }

        private string MeasureBlankCount(string str, Font font)
        {
            Graphics g = this.CreateGraphics();
            float x = g.MeasureString(str, font).Width;
            int i;
            for (i = str.Length; i <= str.Length * 2; i++)
            {
                if (x <= g.MeasureString(new string('1', i), font).Width)
                    break;
            }
            return new string(' ', i);
        }

        private void timerFlash_Tick(object sender, EventArgs e)
        {
            if (flashOn)
            {
	            foreach (string name in this.listFlash)
	            {
                    TreeNode[] result = this.treeViewUsers.Nodes.Find(name, true);
                    foreach (TreeNode node in result)
                    {
                        node.Text = MeasureBlankCount(node.Name, this.treeViewUsers.Font);
                    }
                    int index = this.tabControl1.Controls.IndexOfKey(name);
                    if (index >= 0)
                    {
                        Control ctrl = this.tabControl1.Controls[index];
                        ctrl.Text = MeasureBlankCount(ctrl.Text, ctrl.Font);
                    }
	            }
                flashOn = false;
            } 
            else
            {
                foreach (string name in this.listFlash)
                {
                    TreeNode[] result = this.treeViewUsers.Nodes.Find(name, true);
                    foreach (TreeNode node in result)
                    {
                        node.Text = node.Name;
                    }
                    int index = this.tabControl1.Controls.IndexOfKey(name);
                    if (index >= 0)
                    {
                        this.tabControl1.Controls[index].Text = "与 " + name + " 聊天中";
                    }
                }
                flashOn = true;
            }
        }

        private void OnFileReceiving(object sender, p2p.FileReceivingEventArgs e)
        {
            TriggerPrivateChat(this.session.Name, e.TargetName).AddFileTransfer(e.FileAttr, true);
        }

        #endregion

    }
}